package com.myclasses;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;

import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.data.extensions.When;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

public class CalendarControler {
	private CalendarService service;
	private String user;
	private String password;
	private ArrayList<CalendarEventEntry> cachedEvents;
	
	public CalendarControler(){
		cachedEvents = new ArrayList<CalendarEventEntry>();
	}
		
	
	private static CalendarControler currentInstance = null;
	
	public static CalendarControler getInstance(){
		 if(CalendarControler.currentInstance == null){
			 CalendarControler.currentInstance = new CalendarControler();
		 }
		 return CalendarControler.currentInstance;
	}
	
	private void ensureServiceIsReady(){
		if(service==null)
			authenticate("iosr.team11@gmail.com", "iosr_team");
	}
	
	public boolean authenticate(String user, String password) {
		this.service = new CalendarService("example");
		if(!user.endsWith("@gmail.com")){
			user+="gmail.com";
		}
		this.user = user;
		this.password = password;
		try {
			this.service.setUserCredentials(user, password);
		} catch (AuthenticationException e) {
			return false;
		}
		return true;
	}
	
	private URL getEventFeedUrl() throws MalformedURLException{
		return new URL("http://www.google.com/calendar/feeds/" + this.user+ "/private/full");
	}
	
	public Collection<CalendarEventEntry> downloadAllEvents()
		throws ServiceException, IOException 
	{
		ensureServiceIsReady();
		
		URL eventFeedUrl = 	getEventFeedUrl();
		
	    // Send the request and receive the response:
	    CalendarEventFeed resultFeed = service.getFeed(eventFeedUrl,
	        CalendarEventFeed.class);
	
		this.cachedEvents.clear();
		for (int i = 0; i < resultFeed.getEntries().size(); i++) {
		    CalendarEventEntry entry = resultFeed.getEntries().get(i);
		    cachedEvents.add(entry);
		}
		return this.cachedEvents;
	}
	
	public void addNewEvent(CalendarEventEntry newEvent)
		throws ServiceException, IOException 
	{
		ensureServiceIsReady();
		URL eventFeedUrl = getEventFeedUrl();
		
		this.service.insert(eventFeedUrl, newEvent);
	}
}